<script setup>
import { ref, reactive, watchEffect } from 'vue'
import { Search } from '@element-plus/icons-vue'
import MaterialCode from './code.vue'
import useUserStore from '@/store/modules/user'
import { listUser } from '@/api/system/user.js'
import { RepeatWrapping } from 'three'
const userList = ref([])
const getUser = async () => {
  const res = await listUser({ pageNum: 1, pageSize: 999 })
  userList.value = res.rows.map(item => ({
    label: item.nickName,
    value: item.userId
  }))
  // 默认归属人是当前登录人
  ruleForm.attributor = useUserStore().$state.userId
}

const { proxy } = getCurrentInstance()
const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  },

  isIfKey: {
    type: String,
    default: '新增'
  }
})

if (props.isIfKey != '查看') getUser()
// 封装 方法 字典查询
const {
  sales_order_priority, // 订单优先级
  sales_order_type, // 订单状态
  sale_order_number_rolls, // 销售订单纸管小卷数
  sale_order_deviation, // 	销售订单偏差
  sale_order_packing, // 销售订单包装
  sale_order_quality_standard // 销售订单质量标准
} = proxy.useDict(
  'sales_order_type',
  'sales_order_priority',
  'sale_order_number_rolls',
  'sale_order_deviation',
  'sale_order_packing',
  'sale_order_quality_standard'
)

const emit = defineEmits(['reset', 'submit'])

const customerShow = ref(false)
const materialShow = ref(false)
const title = ref('新增')

const ruleFormRef = ref(null)

const loading = ref(false)

const selection = ref([])
// 新增字段
const ruleForm = reactive({
  // 合同上传 SAT---------------------
  id: '',
  salesContractNum: '', // 销售合同号
  contractUrl: '', // 附件
  // 合同上传 END---------------------
  customerId: '', // 客户id
  orderType: '', // 订单类型
  customerName: '', // 客户
  orderPriority: '', // 订单优先级
  attributor: '', // 归属人
  remark: '', // 备注
  salesOrderDetailList: []
  /**
   *  materialId: '', // 物料id
      materialCode: '', // 物料编码
      widthCloth: '', // 幅宽
      numberRolls: '', // 纸管小卷数
      rollDiameter: '', // 卷径
      thickness: '', // 厚度
      unitPrice: '', // 单价
      planWeight: '', // 计划数量
      deviation: '', // 偏差
      deviationValue: '', // 偏差值
      deliveryDate: '', // 交货日期
      packing: '', // 包装
      qualityStandard: '' // 质量标准
   * 
   */
})

if (props.data?.id) {
  for (let key in props.data) {
    ruleForm[key] = props.data[key]
  }
  if (!ruleForm.orderType) ruleForm.orderType = '1'
  // ruleForm.solution = Number(ruleForm.solution)
} else {
  ruleForm.orderType = '1'
}
const rules = reactive({
  customerId: [{ required: true, message: '请填写客户名称', trigger: 'change' }],
  salesDocumentNum: [{ required: true, message: '订单优先级', trigger: 'change' }],
  reviewComments: [{ required: true, message: '请填写审核意见', trigger: 'bulr' }],
  orderType: [{ required: true, message: '请选择订单类型', trigger: 'change' }],
  orderPriority: [{ required: true, message: '请选择订单优先级', trigger: 'change' }],
  solutionUrl: [{ required: true, message: '请上传附件', trigger: 'change' }]
})

// 客户选择
const customerChange = val => {
  ruleForm.customerName = val.customerName
  ruleForm.customerId = val.id
  close()
}

// 选择的物料
const preservation = row => {
  row.batchNum = ''
  // 去重
  // const arr = row.filter(item => !ruleForm.salesOrderDetailList.some(itemy => itemy.materialId == item.materialId))
  // if (arr.length < 1 && row.length > 0) proxy.warningMsg('选择的数据重复，已自动帮助去重!')
  // ruleForm.salesOrderDetailList.push(...arr)
  row.forEach(item => {
    ruleForm.salesOrderDetailList.push(item)
  })
  console.log(ruleForm.salesOrderDetailList, 'ruleForm.salesOrderDetailList')

  materialShow.value = false
}
// 删除
const remove = () => {
  if (selection.value.length > 0) {
    selection.value.forEach(item => {
      const Find = ruleForm.salesOrderDetailList.findIndex(itemy => item.materialId == itemy.materialId)
      ruleForm.salesOrderDetailList.splice(Find, 1)
    })
  } else {
    ruleForm.salesOrderDetailList.splice(ruleForm.salesOrderDetailList.length - 1, 1)
  }
}
// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  selection.value = selection
}

// 订单类型改变时
const orderTypeChange = () => {
  ruleForm.salesOrderDetailList = []
}

// 提交
const submit = () => {
  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) {
        resolve(false)
        proxy.warningMsg('请填写完整表单')
        return
      }
      //   校验不为空
      if (ruleForm.salesOrderDetailList.length <= 0) {
        proxy.warningMsg('请填写完整明细项')
        resolve(false)
        return
      }

      // const isif = ruleForm.salesOrderDetailList.every(
      //   item =>
      //     item.unitPrice &&
      //     item.planWeight &&
      //     item.deviation &&
      //     item.deviationValue &&
      //     item.deliveryDate &&
      //     item.packing &&
      //     item.qualityStandard
      // )
      // if (!isif) {
      //   console.log('sss')
      //   proxy.warningMsg('请填写完整明细项')
      //   resolve(false)
      //   return
      // }
      // const plannedWeightIsif = ruleForm.salesOrderDetailList.every(
      //   item =>
      //     item.widthCloth > 1 &&
      //     item.numberRolls > 1 &&
      //     item.rollDiameter > 1 &&
      //     item.thickness > 1 &&
      //     item.planWeight > 1
      // )
      // if (!plannedWeightIsif) {
      //   proxy.warningMsg('幅宽 纸管小卷数 卷径 厚度 计划数量不能小于1')
      //   resolve(false)
      //   return
      // }
      //   map仅需要的数据
      // ruleForm.salesOrderDetailList = ruleForm.salesOrderDetailList.map(item => ({
      //   materialId: item.materialId, // 物料id
      //   materialCode: item.materialCode, // 物料编码
      //   widthCloth: item.widthCloth, // 幅宽
      //   numberRolls: item.numberRolls, // 纸管小卷数
      //   rollDiameter: item.rollDiameter, // 卷径
      //   thickness: item.thickness, // 厚度
      //   unitPrice: item.unitPrice, // 单价
      //   planWeight: item.planWeight, // 计划数量
      //   deviation: item.deviation, // 偏差
      //   deviationValue: item.deviationValue, // 偏差值
      //   deliveryDate: item.deliveryDate, // 交货日期
      //   packing: item.packing, // 包装
      //   qualityStandard: item.qualityStandard // 质量标准
      // }))
      resolve(ruleForm)
    })
  })
}

// 新增关闭
const close = () => {
  customerShow.value = false
  materialShow.value = false
}

defineExpose({ submit })
</script>

<template>
  <div class="app-container">
    <el-form
      inline
      scroll-to-error
      ref="ruleFormRef"
      class="demo-ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      label-position="right"
      status-icon
    >
      <el-form-item label="客户信息" prop="customerId">
        <el-input
          :prefix-icon="Search"
          clearable
          :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
          v-model="ruleForm.customerName"
          placeholder="客户信息"
          @click="customerShow = true"
        />
      </el-form-item>
      <el-form-item
        label="销售合同号"
        prop="customerId"
        v-if="props.isIfKey == '合同上传' || props.isIfKey == '查看' || props.isIfKey == '生成发货单'"
      >
        <el-input
          clearable
          :disabled="props.isIfKey !== '合同上传'"
          v-model="ruleForm.salesContractNum"
          placeholder="销售合同号"
        />
      </el-form-item>
      <el-form-item label="订单类别" prop="orderType">
        <el-select
          :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
          clearable
          v-model="ruleForm.orderType"
          placeholder="请选择类别"
          @change="orderTypeChange"
        >
          <el-option v-for="(item, index) in sales_order_type" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单优先级" prop="orderPriority">
        <el-select
          :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
          v-model="ruleForm.orderPriority"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in sales_order_priority"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="归属人" prop="attributor">
        <el-select
          filterable
          :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
          v-model="ruleForm.attributor"
          clearable
          placeholder="请选择"
        >
          <el-option v-for="(item, index) in userList" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <div style="width: 500px">
        <el-form-item label="备注">
          <el-input
            autosize
            clearable
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            v-model="ruleForm.remark"
            :rows="4"
            type="textarea"
            placeholder="请输入备注"
            :input-style="{ width: '500px' }"
          />
        </el-form-item>
      </div>
      <div style="width: 500px">
        <el-form-item label="审核意见" prop="reviewComments" v-if="props.isIfKey == '订单评审'">
          <el-input
            autosize
            clearable
            :disabled="props.isIfKey !== '订单评审'"
            v-model="ruleForm.reviewComments"
            :rows="4"
            type="textarea"
            placeholder="请输入审核意见"
            :input-style="{ width: '500px' }"
          />
        </el-form-item>
      </div>
      <el-form-item
        label="合同上传"
        prop="contractUrl"
        v-if="props.isIfKey == '合同上传' || props.isIfKey == '查看' || props.isIfKey == '生成发货单'"
      >
        <ImageUpload v-model="ruleForm.contractUrl" v-if="props.isIfKey == '合同上传'" />
        <ImagePreview :src="ruleForm.contractUrl" v-else />
      </el-form-item>
      <div style="width: 500px">
        <el-form-item label="关结原因" v-if="props.isIfKey == '查看'">
          <el-input
            autosize
            clearable
            disabled
            v-model="ruleForm.closeReason"
            :rows="4"
            type="textarea"
            placeholder="请输入关结原因"
            :input-style="{ width: '500px' }"
          />
        </el-form-item>
      </div>
    </el-form>
    <!-- 明细项 -->
    <div class="flex-items-center flex-between" v-if="props.isIfKey == '修改' || props.isIfKey == '新增'">
      <div class="title">明细项</div>
      <div class="flex-between" v-if="!props.db">
        <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
          <el-icon @click="materialShow = true"><Plus /></el-icon>
        </el-tooltip>
        <div style="margin: 0 10px"></div>
        <el-tooltip class="box-item" effect="dark" content="勾选删除" placement="top-start">
          <el-icon @click="remove()"><Minus /></el-icon>
        </el-tooltip>
      </div>
    </div>
    <el-table
      v-if="props.isIfKey != '单据明细修改'"
      v-loading="loading"
      stripe
      border
      :data="ruleForm.salesOrderDetailList"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" align="center" />
      <el-table-column label="产品编码" prop="materialCode" width="220" align="center" />
      <el-table-column label="产品名称" prop="materialName" width="220" align="center" />
      <el-table-column label="产品规格" prop="materialSpec" width="220" align="center" />
      <el-table-column label="规格型号" prop="specType" width="220" align="center" />
      <el-table-column label="订单数量(个)" width="220" align="center">
        <template #default="scope">
          <el-input
            type="number"
            :min="0"
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            clearable
            v-model="scope.row.planWeight"
          />
        </template>
      </el-table-column>
      <el-table-column label="可用库存数" width="220" align="center">
        <template #default="scope">
          <el-input type="number" :min="0" disabled clearable v-model="scope.row.planWeight1" />
        </template>
      </el-table-column>

      <el-table-column label="单价" width="220" align="center">
        <template #default="scope">
          <el-input
            type="number"
            :min="0"
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            clearable
            v-model="scope.row.unitPrice"
          />
        </template>
      </el-table-column>
      <el-table-column label="交货日期" width="220" align="center">
        <template #default="scope">
          <el-date-picker
            clearable
            v-model="scope.row.deliveryDate"
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            type="datetime"
            placeholder="请选择时间"
            format="YYYY/MM/DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品行备注" width="220" align="center">
        <template #default="scope">
          <el-input
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            clearable
            v-model="scope.row.remark"
            :rows="2"
            type="textarea"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-table
      v-if="props.isIfKey == '单据明细修改'"
      v-loading="loading"
      border
      :data="ruleForm.salesOrderDetailList"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" align="center" />
      <el-table-column label="产品编码" prop="materialCode" width="220" align="center" />
      <el-table-column label="产品名称" prop="materialName" width="220" align="center" />
      <el-table-column label="产品规格" prop="materialSpec" width="220" align="center" />
      <el-table-column label="规格型号" prop="specType" width="220" align="center" />
      <el-table-column label="订单数量(个)" width="220" align="center">
        <template #default="scope">
          <el-input
            type="number"
            :min="0"
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            clearable
            v-model="scope.row.planWeight"
          />
        </template>
      </el-table-column>

      <el-table-column label="可用库存数" width="220" align="center">
        <template #default="scope">
          <el-input type="number" :min="0" disabled clearable v-model="scope.row.planWeight1" />
        </template>
      </el-table-column>

      <el-table-column label="单价" width="220" align="center">
        <template #default="scope">
          <el-input
            type="number"
            :min="0"
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            clearable
            v-model="scope.row.planWeight2"
          />
        </template>
      </el-table-column>

      <el-table-column label="交货日期" width="220" align="center">
        <template #default="scope">
          <el-date-picker
            clearable
            v-model="scope.row.deliveryDate"
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            type="datetime"
            placeholder="请选择时间"
            format="YYYY/MM/DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品行备注" width="220" align="center">
        <template #default="scope">
          <el-input
            :disabled="!(props.isIfKey == '新增' || props.isIfKey == '修改')"
            clearable
            v-model="scope.row.remark"
            :rows="2"
            type="textarea"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 客户 -->
    <Customer :is-show="customerShow" @preservation="customerChange" @cancel="customerShow = false" />
    <!-- 物料选择 -->
    <p-XiaoheDialog :dialogVisible="materialShow" title="物料选择" width="65%" @close="close">
      <template #body>
        <MaterialCode
          :type="ruleForm.orderType"
          @cancel="close"
          @preservation="preservation"
          :dictKey="'sales_order_type'"
        />
      </template>
    </p-XiaoheDialog>
  </div>
</template>

<style lang="scss" scoped>
.tableInput {
  width: 195px;
}
</style>
